package com.demo.randomdining

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.demo.randomdining.dao.TargetDB
import com.demo.randomdining.databinding.ActivitySelectBinding
import com.demo.randomdining.databinding.TextItemViewBinding
import com.demo.randomdining.model.TargetInfo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class SelectActivity : AppCompatActivity() {
    private lateinit var binding: ActivitySelectBinding
    private lateinit var targetDB: TargetDB

    private lateinit var adapter: RcvAdapter

    class RcvAdapter : BaseAdapter {
        private var data = mutableListOf<TargetInfo>()
        private var checkList = mutableListOf<TargetInfo>()
        private var callBack: CallBack? = null


        public fun setCallBack(callBack: CallBack) {
            this.callBack = callBack
        }

        constructor(data: List<TargetInfo>) : super() {
            this.data.addAll(data)
        }

        override fun getCount(): Int {
            return data.size
        }

        override fun getItem(position: Int): TargetInfo {
            return data[position]
        }

        override fun getItemId(position: Int): Long {
            return data[position].targetId
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            var view: View? = null
            if (convertView == null) {
                val layoutInflater = LayoutInflater.from(parent?.context)
                val binding = TextItemViewBinding.inflate(layoutInflater, parent, false)
                view = binding.root
            } else {
                view = convertView
            }
            val bind = TextItemViewBinding.bind(view)
            val item = getItem(position)
            bind.tvName.text = item.name
            bind.btnRemove.setOnClickListener {
                CoroutineScope(Dispatchers.IO).launch {
                    TargetDB.getInstance(bind.root.context).targetDao.delete(item)
                    launch(Dispatchers.Main) {
                        data.remove(item)
                        notifyDataSetChanged()
                    }
                }
                callBack?.onDelete()
            }
            bind.cbFood.setOnCheckedChangeListener(null)
            bind.cbFood.isChecked = checkList.contains(item)
            bind.cbFood.setTag(Int.MIN_VALUE, item)
            bind.cbFood.setOnCheckedChangeListener { buttonView, isChecked ->
                var item: TargetInfo = bind.cbFood.getTag(Int.MIN_VALUE) as TargetInfo
                if (isChecked) {
                    checkList.add(item)
                } else {
                    checkList.remove(item)
                }
                callBack?.onSelect()
            }

            bind.cbFood.visibility = View.VISIBLE
            return view;
        }

        fun add(info: TargetInfo) {
            data.add(info)
            notifyDataSetChanged()
        }

        fun getSelectListSize(): Int {
            return checkList.size
        }

        fun getSelectList(): MutableList<TargetInfo> {
            return checkList
        }

        fun getList(): MutableList<TargetInfo> {
            return data
        }

        interface CallBack {
            fun onDelete()
            fun onSelect()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySelectBinding.inflate(layoutInflater)
        setContentView(binding.root)

        targetDB = TargetDB.getInstance(this)
        binding.btnAdd.setOnClickListener {
            val trim = binding.etFood.text.toString().trim()
            if (TextUtils.isEmpty(trim)) {
                toast("店名不能为空")
                return@setOnClickListener
            }
            val item = targetDB.targetDao.getInfo(trim)
            if (item.isNotEmpty()) {
                toast("店名不能重复")
                return@setOnClickListener
            }

            CoroutineScope(Dispatchers.IO).launch {
                var info = TargetInfo()
                info.name = trim
                targetDB.targetDao.insert(info)
                launch(Dispatchers.Main) {
                    adapter.add(info)
                    binding.etFood.text.clear()
                }
            }
        }
        binding.btnStart.setOnClickListener {
            var size = adapter.getSelectListSize()
            if (size == 0) {
                var intent = Intent(SelectActivity@ this, MainActivity::class.java)
                startActivity(intent)
            } else {
                var intent = Intent(SelectActivity@ this, MainActivity::class.java)
                intent.putExtra("list", ArrayList(adapter.getSelectList()))
                startActivity(intent)
            }
        }
        val all = targetDB.targetDao.getAll()
        adapter = RcvAdapter(all)
        adapter.setCallBack(object : RcvAdapter.CallBack {
            override fun onDelete() {

            }

            override fun onSelect() {
                binding.tvSelect.text = if (adapter.getSelectListSize() == 0) {
                    "已选择全部"
                } else {
                    "已选择${adapter.getSelectListSize()}个"
                }
            }

        })
        binding.rcvFood.adapter = adapter

    }

    private fun toast(str: String) {
        Toast.makeText(MainActivity@ this, str, Toast.LENGTH_SHORT).show()
    }

}